import datetime

import pymysql

from db import DB
from lolita.PostPublish import saveBili2Post

originDB = DB.getOriginDB()

bilibiliCollection = originDB.lolita_bilibili

sql = "INSERT INTO `lo_data_bilibili` (`title`,`description`,`cover`,`src`,`author`,`author_url`,`length` ,`date`) VALUES (%s, %s,%s, %s,%s, %s,%s, %s)"

querySql = "SELECT `src` FROM `lo_data_bilibili` WHERE `src`=%s"


def operateBili():
    mysqlCon = pymysql.Connect(
        host='rm-bp10684y5104946w7o.mysql.rds.aliyuncs.com',
        user='root',
        password="Xmtj6666",
        database='lolita',
        port=3306,
        charset='utf8mb4',
    )
    mysqlCur = mysqlCon.cursor()

    global bilibiliCollection
    i = 1
    alls = bilibiliCollection.find()
    for one in alls:
        mysqlCur.execute(querySql, one['video_url'][0])
        result = mysqlCur.fetchone()
        if result:
            print("已经添加了该视频！")
            break
        date = datetime.datetime.fromtimestamp(one['created'])
        c = (one['title'], one['description'], "http:" + one['pic'], one['video_url'][0], one['author'],
             one['user_url'], one['length'], date)
        mysqlCur.execute(sql, c)
        mysqlCon.commit()
        print("bilibili已经添加了%s条", i)
        i += 1
        saveBili2Post(date, one['title'], one['video_url'][0], "http:" + one['pic'], one['length'], one['author'],
                      one['user_url'], one['description'])
    mysqlCon.close()


if __name__ == "__main__":
    operateBili()
